package model;

import java.util.HashMap;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import javax.swing.table.AbstractTableModel;

import domain.Customer;
import domain.Library;
import domain.Loan;

public class LoansOfPersonTableModel extends AbstractTableModel implements Observer {
    private static HashMap<Customer, LoansOfPersonTableModel> instance = new HashMap<>();
    private String[] columns = { "ID", "Titel", "Autor" };
    private List<Loan> model;
    private final Library library;
    private static final long serialVersionUID = 2966279676059941187L;
    private final Customer customer;

    public static LoansOfPersonTableModel getInstance(Customer customer) {
        if (!instance.containsKey(customer))
            instance.put(customer, new LoansOfPersonTableModel(customer));
        return instance.get(customer);
    }

    private LoansOfPersonTableModel(Customer customer) {
        this.customer = customer;
        library = Library.getInstance();
        library.addObserver(this);
        model = library.getCustomerOpenLoans(this.customer);
        this.update(null, null);
    }

    @Override
    public void update(Observable obj, Object arg1) {
        model = library.getCustomerOpenLoans(this.customer);
        this.fireTableDataChanged();
    }

    @Override
    public boolean isCellEditable(int arg0, int arg1) {
        return false;
    }

    @Override
    public String getColumnName(int column) {
        return columns[column];
    }

    @Override
    public int getColumnCount() {
        return columns.length;
    }

    @Override
    public int getRowCount() {
        return model.size();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Loan loan;
        loan = model.get(rowIndex);
        switch (columnIndex) {
            case 0:
                return loan.getCopy().getInventoryNumber();
            case 1:
                return loan.getCopy().getTitle().getName();
            case 2:
                return loan.getCopy().getTitle().getAuthor();
            default:
                return null;
        }
    }

    public Loan getElementAt(int rowIndex) {
        return model.get(rowIndex);
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        switch (columnIndex) {
            case 0:
                return Integer.class;
            case 1:
            case 2:
                return String.class;
            default:
                return null;
        }
    }

}
